package com.iepacj.pattern.observer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by iEpac on 16/6/12.
 */
public class WeatherData implements Subject {

    /**
     * 用来记录观察者
     */
    private List<Observer> observers;

    private float temp;

    private float humidity;

    private float pressure;


    public WeatherData() {
        this.observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {

        int index = observers.indexOf(o);
        if (index >= 0) {
            observers.remove(index);
        }

    }

    /**
     * 把状态值告诉每一个观察者
     * 因为观察者都实现了update方法
     * 所以我们知道如何通知他们
     */
    @Override
    public void notifyObserver() {

        for (int i = 0; i < observers.size(); i++) {
            Observer observer = observers.get(i);
            observer.update(temp, humidity, pressure);
        }

    }

    /**
     * 当从气象站得到得到更新的观测值时, 通知观察者
     */
    public void measurementsChanged() {
        notifyObserver();
    }


    public void setMeasurements(float temp, float humidity, float pressure) {
        this.temp = temp;
        this.humidity = humidity;
        this.pressure = pressure;
        measurementsChanged();
    }
}



















